package juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/30
 * Time:10:02
 * 循环屏障示例
 **/
public class Demo3 {
    public static void main(String[] args) {

        //创建循环屏障
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("执行了CyclicBarrier里边的Runnable");
            }
        });

        for (int i = 1; i < 11; i++) {
            final int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"开始起跑");
                    try {
                        Thread.sleep(finalI*200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    try {
                        System.out.println(Thread.currentThread().getName()+"等待其他人----------");
                        //计数器-1
                        //判断计数器是否为0
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }

                    //说明已经冲破了栅栏、
                    //执行到这，说明已经有一种线程满足条件了
                    System.out.println(Thread.currentThread().getName()+"到达终点。。。。。。");
                }
            }).start();
        }
    }

}
